package com.coollang.smartbra.utils;

import android.os.Handler;
import android.os.Message;

/**
 * Created by Administrator on 2016/10/27 0027.
 */

public class LockTimerUitls {

    public long timer = 0; // 跑步的时间
    public long startTimer = 0;// 开始时间
    public Thread thread; // 控制时间的子线程
    private static LockTimerUitls instance;// 创建单例
    private TimeListener mTimeListener;// 设置时间的监听器

    private LockTimerUitls() {
    }

    public static LockTimerUitls getInstance() {
        if (instance == null) {
            instance = new LockTimerUitls();
        }
        return instance;
    }

    public Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            // 在UI中设置时间
            if (mTimeListener != null) {
                mTimeListener.onLockTimeChange();
            }
        }
    };

    public void initTime() {
        if (thread == null) {
            startTimer = System.currentTimeMillis();
            thread = new Thread() {
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (startTimer != System.currentTimeMillis()) {
                            timer = System.currentTimeMillis() - startTimer;
                        }
                        Message msg = new Message();
                        handler.sendMessage(msg);// 通知主线程
                    }
                }
            };
            thread.start();
        }
    }

    public interface TimeListener {
        void onLockTimeChange();
    }

    public void setTimeListener(TimeListener mTimeListener) {
        this.mTimeListener = mTimeListener;
    }

    // 结束
    public void stopTimer() {
        handler.removeCallbacks(thread);
        mTimeListener = null;
        thread = null;
        timer = 0;
    }
}
